package agents.task;

import java.util.ArrayList;
import java.util.List;

import agents.Ant;
import agents.resource.ResourceAgent;
import domain.TimeInterval;

// ant zal zich opsplitsen per uitgaande route en update route-info
class ExitResourceAnt extends ExplorationAnt {

	public ExitResourceAnt(Trip trip, ExplorationAnt parentAnt) {
		super(parentAnt.getCurrentResource(),parentAnt);
		setTrip(trip);
		setHopsLeft(getHopsLeft()-1);
	}
	
	@Override
	public void doStep() {
		if(getCurrentResource().hasSegment(getDestination()) || getHopsLeft() == 0) { //einde van de trip van de ant
			long enterTime = getTrip().getLastStep().getEnterTime();
			TimeInterval exitInterval = getCurrentResource().getPossibleExitInterval(enterTime,getOrigin().getCar());
			if(exitInterval != null) {
				getTrip().append(new TripStep(null,exitInterval.getStartTime()+1)); //moment dat de volgende resource wordt binnengegaan toevoegen
				long estimatedTimeLeft = getCurrentResource().getEstimatedTimeTo(getDestination());
				if(estimatedTimeLeft != -1) { //als er mogelijk een route is
					getTrip().setEstimatedTimeLeft(estimatedTimeLeft);
					getOrigin().notifyExplorationAntArrival(this);
				}
			}
		} else { //verder gaan naar outgoing resources
			createChildAnts();
		}
		terminate();
	}
	
	public void createChildAnts() {
		long enterTime = getTrip().getLastStep().getEnterTime();
		TimeInterval exitInterval = getCurrentResource().getPossibleExitInterval(enterTime,getOrigin().getCar());
		if(exitInterval == null) {
			return;
		} else {
			exitInterval = exitInterval.shift(1);
		}
		
		List<ResourceAgent> outs = getCurrentResource().getOutgoingResources();
		List<Ant> children = new ArrayList<Ant>();
		for(ResourceAgent out : outs) {
			if(!getTrip().passesBy(out) && out != getOrigin().getCurrentResource()) { //niet in cirkels lopen
				children.add(new EnterResourceAnt(out,exitInterval,this));
			}
		}
		setChildAnts(children);
	}
}
